package th.retrofit.lib;

public class CharSolution {

    /**
     * 压缩字符串
     * https://leetcode-cn.com/problems/string-compression/
     * 压缩前：{'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd', 'e'}
     * 压缩后：ab3c2d2e
     * @param chars 待压缩的字符串
     * @return 压缩后的长度
     */
    public int compress1(char[] chars) {
        int length = chars.length;
        int i = 0, index = 0;
        for (int j = 0; j < length; j ++) {
            if (j == length - 1 || chars[j] != chars[j + 1]) {
                chars[index++] = chars[j];
                int count = j - i + 1;
                if (count > 1) {
                    int anchor = index;
                    while (count != 0) {
                        chars[index++] = (char) ('0' + (count % 10));
                        count /= 10;
                    }
                    reverse(chars, anchor, index - 1);
                }
                i = j + 1;
            }
        }
        return index;
    }

    public void reverse(char[] chars, int left, int right) {
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        char[] chars = {'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd', 'e'};
//        char[] chars = {'a', 'b', 'c'};
        int length = new CharSolution().compress1(chars);
        for (int i = 0; i < length; i++) {
            System.out.printf("%c, ", chars[i]);
        }
        System.out.println();
        System.out.println((char)('0' + length));
    }
}
